import {resMessage, sendRead, wsData} from "../type/websocket";
import {useFriendStore} from "../store/friend";
import {showNotify} from "vant";
import {useChatStore} from "../store/chat";

let socket: WebSocket|undefined

// 创建socket   单例
export function CreateSocket(): WebSocket {
    const token = localStorage.getItem("token")
    if (socket == undefined || token !== null) {
        socket = new WebSocket(`ws://${location.host}/api/ws`, [token as string])

        socket.addEventListener("message", function (e) {
            // console.log(e.data)
            // json序列化
            const data = JSON.parse(e.data) as wsData<any>

            switch (data.type) {
                case 0: {
                    // 错误消息
                    break
                }
                case 1: {
                    // 聊天消息
                    const d = data.data as resMessage
                    // 实例化仓库
                    const friendStore = useFriendStore()
                    // 判断聊天文档是否为同一个，如果是，则追加

                    if (friendStore.friendChat?.chat.id == d.chat_id) {
                        // 为当前聊天，追加聊天消息
                        friendStore.pushFriendChat(d.chat)

                        // 告诉服务器，消息已被读取
                        const sendData: wsData<sendRead> = {
                            type: 3,
                            data: {
                                friend_id: d.user.id,
                                chat_id: d.chat_id
                            }
                        }
                        socket?.send(JSON.stringify(sendData))
                    } else {
                        // 不是当前会话，提示用户接到新通知
                        showNotify({
                            type: "primary",
                            // @ts-ignore
                            "z-index": 9999,
                            message: `${d.user.name}:${d.chat.msg}`,
                        });

                        // 刷新数据
                        // 实例化 好友仓库
                        const friendStore = useFriendStore()
                        // 获取好友列表
                        friendStore.getFriendList()
                    }

                    break
                }
            }
        })

        socket.addEventListener("close",()=>{
            // 连接关闭，将其销毁
            socket = undefined
        })
    }

    return socket
}